package com.example.springboot2.repository;

import com.example.springboot2.entity.Coupon;
import com.example.springboot2.entity.Merchant;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 优惠券Repository
 */
@Repository
public interface CouponRepository extends JpaRepository<Coupon, Long>, JpaSpecificationExecutor<Coupon> {

    /**
     * 根据商家查找优惠券
     */
    Page<Coupon> findByMerchant(Merchant merchant, Pageable pageable);

    /**
     * 根据商家和状态查找优惠券
     */
    Page<Coupon> findByMerchantAndStatus(Merchant merchant, Coupon.CouponStatus status, Pageable pageable);

    /**
     * 查找有效的优惠券
     */
    @Query("SELECT c FROM Coupon c WHERE c.merchant = :merchant AND c.status = 'ONGOING' AND c.startTime <= :now AND c.endTime >= :now AND c.usedQuantity < c.totalQuantity")
    List<Coupon> findValidCouponsByMerchant(@Param("merchant") Merchant merchant, @Param("now") LocalDateTime now);

    /**
     * 统计商家优惠券数量
     */
    long countByMerchant(Merchant merchant);

    /**
     * 统计商家指定状态优惠券数量
     */
    long countByMerchantAndStatus(Merchant merchant, Coupon.CouponStatus status);
}
